package com.kushe.site.controller;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.kushe.config.Config;
import com.kushe.dao.DesignDao;
import com.kushe.dao.ImagesDao;
import com.kushe.dao.SortDao;
import com.kushe.dao.UserDao;
import com.kushe.entity.Design;
import com.kushe.entity.Images;
import com.kushe.entity.Sort;
import com.kushe.entity.User;
import com.kushe.util.ImagesUtil;
import com.kushe.util.KSController;
import com.kushe.util.SessionEnv;
import com.kushe.util.core.DaoFactory;
import com.kushe.util.core.DbUtils;
import com.kushe.util.core.FileManager;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * Created by WhiteBlue on 15/5/14.
 */
@org.springframework.stereotype.Controller
@RequestMapping(value = "/img")
public class ImagesController extends KSController {

    /**
     * 得到所有素材
     */
    @RequestMapping(value = "listAll", method = RequestMethod.GET)
    public Object listAll() {
        ImagesDao dao = DaoFactory.getDao(ImagesDao.class);
        List<Images> list = (List<Images>) dao.listByPage(1).getList();
        this.setAttr("list", list);
        return this.render("/img/listAll.html");
    }


    /**
     * 素材分页(json返回)
     */
    @RequestMapping(value = "more", method = RequestMethod.GET)
    @ResponseBody
    public Object getMore(@RequestParam(value = "page", required = true) int page, HttpServletResponse response) {
        ImagesDao dao = DaoFactory.getDao(ImagesDao.class);
        List<Images> list = (List<Images>) dao.listByPage(page + 1).getList();
        Map[] jsonList = new Map[list.size()];
        Map<String, Object> json = new HashMap<String, Object>();

        for (int i = 0; i < list.size(); i++) {
            Map<String, Object> imgJson = new HashMap<String, Object>();
            imgJson.put("themeId", list.get(i).getId());
            imgJson.put("themeName", list.get(i).getTitle());
            imgJson.put("themeSrc", "#");
            imgJson.put("imgSrc", list.get(i).getImg());
            imgJson.put("desc", list.get(i).getTitle());
            jsonList[i] = imgJson;
        }
        json.put("themes", jsonList);
        return json;
    }


    /**
     * 添加新素材(json返回)
     */
    @RequestMapping(value = "addImg", method = RequestMethod.POST)
    @ResponseBody
    public Object addImg(@RequestParam(value = "title", required = true) String title, @RequestParam(value = "content", required = true) String file, HttpServletRequest request, HttpServletResponse response) {
        String basePath = request.getServletContext().getRealPath("/");
        File img = new File(basePath + Config.TEMP_DIR);

        boolean flag;
        Map<String, Object> json = new HashMap<String, Object>();
        flag = (file.length() > 1024 * 500) && (file.length() < 1024 * 1024 * 3);
        if (flag) {
            img = ImagesUtil.BytesToFile(file, img);
            flag = (img != null);
            if (flag) {
                flag = ImagesUtil.putImage(img);
                if (flag) {
                    User user = ((SessionEnv) request.getSession().getAttribute("sessionEnv")).getUser();
                    ImagesDao imagesDao = DaoFactory.getDao(ImagesDao.class);
                    imagesDao.addImages(ImagesUtil.yun_url + img.getName(), user.getId(), title);

                    json.put("status", true);
                    return json;
                }
            }
        }

        json.put("status", false);
        return json;
    }


    //添加设计图片
    @RequestMapping(value = "addDesignImg", method = RequestMethod.POST)
    @ResponseBody
    public Object addDesignImg(@RequestParam(value = "content", required = false) String file, HttpServletRequest request, HttpServletResponse response) {
        SessionEnv env = (SessionEnv) request.getSession().getAttribute("sessionEnv");
        String basePath = request.getServletContext().getRealPath("/");

        Map<String, Object> json = new HashMap<String, Object>();

        try {
            File img = new File(basePath + Config.TEMP_DIR);

            img = ImagesUtil.BytesToFile(file, img);

            if ((env.getFile1() == null) && (env.getFile2() == null)) {
                env.setFile1(img);
                json.put("result", 1);
                return json;
            } else if ((env.getFile1() != null) && (env.getFile2() == null)) {
                env.setFile1(img);
                json.put("result", 2);
                return json;
            } else {
                env.clearFiles();
                env.setFile1(img);
                json.put("result", 0);
                return json;
            }
        } catch (Exception e) {
            e.printStackTrace();
            json.put("result", false);
            return json;
        }
    }


    //确认添加设计
    @RequestMapping(value = "conformDesign", method = RequestMethod.POST)
    @ResponseBody
    public Object addDesign(@RequestParam(value = "title", required = true) String title,
                            @RequestParam(value = "content", required = false) String content,
                            @RequestParam(value = "sort", required = true) int sort_id,
                            HttpServletRequest request, HttpServletResponse response) {
        SessionEnv env = (SessionEnv) request.getSession().getAttribute("sessionEnv");

        Sort sort = DaoFactory.getDao(SortDao.class).get(sort_id);

        User user = env.getUser();

        Map<String, Object> json = new HashMap<String, Object>();
        DesignDao designDao = DaoFactory.getDao(DesignDao.class);

        if (sort != null && env.getFile1() != null && env.getFile2() != null)
            try {
                if (ImagesUtil.putImage(env.getFile1()) && ImagesUtil.putImage(env.getFile2())) {
                    Design design = designDao.addDesign(title, Config.PRICE, content, user.getId(), sort.getId(), sort.getCategory_id(), ImagesUtil.yun_url + env.getFile1().getName(), ImagesUtil.yun_url + env.getFile2().getName());//添加设计
                    json.put("result", 1);
                    json.put("designId", design.getId());
                    return json;
                } else {
                    json.put("result", 0);
                    return json;
                }
            } catch (Exception e) {
                json.put("result", 2);
                return json;
            }
        else {
            json.put("result", 3);
            return json;
        }
    }


    @RequestMapping(value = "changeHead", method = RequestMethod.POST)
    @ResponseBody
    public Object changeHead(@RequestParam(value = "content", required = true) String file, HttpServletRequest request, HttpServletResponse response) {
        String basePath = request.getServletContext().getRealPath("/");
        File img = new File(basePath + Config.TEMP_DIR);

        boolean flag;
        Map<String, Object> json = new HashMap<String, Object>();
        flag = (file.length() > 10000);
        if (flag) {
            img = ImagesUtil.BytesToFile(file, img);
            flag = (img != null);
            if (flag) {
                flag = ImagesUtil.putImage(img);
                if (flag) {
                    User user = (User) request.getSession().getAttribute("sessionEnv");
                    UserDao userDao = DaoFactory.getDao(UserDao.class);
                    userDao.changeHead(user, ImagesUtil.yun_url + img.getName());

                    json.put("status", true);
                    return json;
                }
            }
        }

        json.put("status", false);
        return json;
    }

//    @RequestMapping(value = "delete", method = RequestMethod.GET)
//    public Object deleteImages(@RequestParam(value = "img", required = true) int imagesId, HttpServletRequest request, HttpServletResponse response) {
//        ImagesDao dao = DaoFactory.getDao(ImagesDao.class);
//        Images images = dao.get(imagesId);
//        if (images != null) {
//            String basePath = request.getServletContext().getRealPath("/");
//            File file = null;
//            file = FileManager.getFile(images.getImg(), basePath + Config.IMG_DIR);
//
//            file.delete();
//            DbUtils.getNutzDao().delete(images);
//            return renderJson(response, true);
//        } else {
//            return renderJson(response, false);
//        }
//    }


}
